package com.lazydong.apiforward.jpackage.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.lazydong.apiforward.jpackage.enums.BatEnum;
import com.lazydong.apiforward.jpackage.enums.ModuleEnum;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class PackageUtil {

    private static final String javaDirPath = "C:\\Program Files\\Java\\jdk-21";
    private static final String mavenDirPath = "D:\\apache-maven";
    private static final String currDir = System.getProperty("user.dir");

    public static final String exeInPath = System.getProperty("user.dir") + File.separator + "exeIn";
    public static final String exeOutPath = System.getProperty("user.dir") + File.separator + "exeOut";
    public static final String exeZipPath = System.getProperty("user.dir") + File.separator + "exeZip";

    public static final String BAT_BASE_PATH = System.getProperty("user.dir") + File.separator + "exeBat";

    // 设置字符编码为 GBK（根据实际情况调整）
    private static final Charset charset = Charset.forName("GBK");


    /**
     * 第一步，复制文件
     *
     * @param moduleEnum moduleEnum
     */
    public static void copyFile(ModuleEnum moduleEnum, String buildDirectory) {
        FileUtil.del(exeInPath);
        FileUtil.mkdir(exeInPath);
        // 复制文件
        System.out.println("开始复制文件...");
        String jarPath = buildDirectory + File.separator + moduleEnum.jarName;
        FileUtil.copy(jarPath, exeInPath, true);
        String libsPath = buildDirectory + File.separator + "libs";
        if (FileUtil.exist(libsPath)) {
            FileUtil.copy(libsPath, exeInPath, true);
        }
    }

    /**
     * 执行脚本
     *
     * @param batEnum batEnum
     * @param module  module
     */
    public static void runBat(BatEnum batEnum, ModuleEnum module) {
        // 写入图标
        String tempIcon = BAT_BASE_PATH + File.separator + module.iconName;
        BufferedOutputStream outputStream = FileUtil.getOutputStream(tempIcon);
        BufferedInputStream inputStream = FileUtil.getInputStream("favicon.ico");
        IoUtil.copy(inputStream, outputStream);
        IoUtil.close(outputStream);
        IoUtil.close(inputStream);
        // 写入脚本
        String batPath = BAT_BASE_PATH + File.separator + batEnum.batName;
        File file = FileUtil.file(batEnum.batName);
        String batContent = FileUtil.readString(file, StandardCharsets.UTF_8);
        String pomPath = currDir + File.separator + module.moduleName + File.separator + "pom.xml";
        Map<String, String> placeholderValues = new HashMap<>();
        if (batEnum == BatEnum.J_PACKAGE) {
            // jpackage --type app-image --input {inputDir} --name {name} --main-jar {mainJar} --main-class {mainClass} --dest {outputDir}
            placeholderValues.put("disk", javaDirPath.substring(0, 2));
            placeholderValues.put("JAVA_HOME", javaDirPath);
            placeholderValues.put("inputDir", exeInPath);
            placeholderValues.put("name", module.moduleName);
            placeholderValues.put("mainJar", module.jarName);
            placeholderValues.put("mainClass", module.mainClass);
            placeholderValues.put("outputDir", exeOutPath);
            placeholderValues.put("icon", tempIcon);
            batContent = StrUtil.format(batContent, placeholderValues);
        } else {
            placeholderValues.put("MAVEN_HOME", mavenDirPath);
            placeholderValues.put("POM_PATH", pomPath);
            batContent = StrUtil.format(batContent, placeholderValues);
        }
        // 写入脚本
        FileUtil.writeString(batContent, BAT_BASE_PATH + File.separator + batEnum.batName, StandardCharsets.UTF_8);
        // 执行脚本
        doSyncRunBat(batPath, module);
    }

    public static void doSyncRunBat(String batPath, ModuleEnum module) {
        FileUtil.del(exeOutPath + File.separator + module.moduleName);
        try {
            // 指定批处理文件的路径和参数（如果有的话）
            ProcessBuilder builder = new ProcessBuilder(batPath);
            builder.redirectErrorStream(true); // 将错误输出和标准输出合并
            Process process = builder.start();
            // 读取输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待进程结束
            int exitCode = process.waitFor();
            System.out.println("Exited with code: " + exitCode);
            if (exitCode != 0) {
                throw new RuntimeException("执行失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 压缩文件
     */
    public static void zipExe(ModuleEnum moduleEnum) {
        String exeZip = exeZipPath + File.separator + moduleEnum.zipName;
        if (!FileUtil.exist(exeZip)) {
            FileUtil.touch(exeZip);
        }
        ZipUtil.zip(exeOutPath + File.separator + moduleEnum.moduleName, exeZip);
    }
}
